import { UserConfig } from '@/api';
import { GetUserInfo, MoneyTxPoints } from '@/api/user';
import { Button, Field, Icon, Popup } from '@antmjs/vantui';
import { Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { useMemo, useState } from 'react';
import { useRequest } from 'taro-hooks';
import { RoleType } from 'types/user';

export default function (props: { onSuccess: Function }) {
  const [show, setShow] = useState<boolean>(false);
  const { data: user, refresh: refreshUser } = useRequest(GetUserInfo, {
    cacheKey: 'get:user:info',
  });

  // *是否提现中
  const txing = useMemo(() => (user?.txing_points ? true : false), [user]);

  const [integral, setIntegral] = useState<number | undefined>(undefined);
  const [errorMessage, setErrorMessage] = useState<string>();

  const { runAsync, loading } = useRequest(MoneyTxPoints, {
    manual: true,
  });

  //获取配置
  const { data: proportion } = useRequest(() => UserConfig({ type: 6 }));

  //当前输入可兑换多少？
  const calcMoney = useMemo(
    () => (integral || 0) / (proportion || 0),
    [proportion, integral]
  );

  //当前可输入的最大积分
  const maxPoint = useMemo(() => {
    if (user?.role === RoleType.专家 || user?.role === RoleType.合伙人)
      return user.points;
    return (user?.max_points || 0) > (user?.points || 0)
      ? user?.points
      : user?.max_points || 0;
  }, [user]);

  function handleClose() {
    setShow(false);
    setIntegral(undefined);
    setErrorMessage(undefined);
    refreshUser();
  }

  function renderNode() {
    return (
      <Popup
        show={show}
        round
        position='bottom'
        className='p-4'
        style={{
          overflow: 'initial',
        }}
        onClose={() => handleClose()}
      >
        <Icon
          name='close'
          onClick={() => handleClose()}
          className=' absolute right-2 -top-[90px] text-3xl text-white'
        />
        <Text className=' text-lg font-bold text-black block mb-2'>
          积分兑换申请
        </Text>

        <View
          className='px-4 py-8 pb-4 border-[2px] border-solid border-[rgba(70,109,180,0.2)] rounded-lg mb-4 mt-8 relative'
          style={{
            background:
              'linear-gradient(180deg, rgba(179,199,248,0.42) 0%, rgba(196,213,253,0.48) 44%, rgba(213,223,249,0.17) 100%)',
          }}
        >
          <View
            className='w-[268px] h-[58px] leading-[52px] bg-cover absolute -top-[20px] left-1/2 -translate-x-1/2  text-black font-bold text-center text-lg'
            style={{
              backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/title-bg-1.png)`,
            }}
          >
            兑换积分数
          </View>

          {user?.role === RoleType.用户 && (
            <View className=' rounded-lg p-2 bg-[rgba(255,255,255,.4)] text-xs text-gary4 mx-4 mb-4'>
              您本月最多可兑换
              <Text className='text-primary font-bold mx-1'>
                {user?.max_points}
              </Text>
              积分，已兑换{' '}
              <Text className='text-primary font-bold mx-1'>
                {user?.tx_points}
              </Text>
              积分，剩余可兑换额度为
              <Text className='text-primary font-bold mx-1'>
                {user?.left_points}
              </Text>
              积分
            </View>
          )}

          <Field
            disabled={txing}
            errorMessage={errorMessage}
            onChange={(e) => {
              setErrorMessage(undefined);
              setIntegral(e.detail);
              if (e.detail === '') return setErrorMessage(undefined);
              const value = Number(e.detail || 0);
              if (value <= 0) return setErrorMessage('积分不得小于等于0');
              if (!Number.isInteger(value))
                return setErrorMessage('不可以输入小数');
              if (value > (maxPoint || 0))
                return setErrorMessage(`积分不得超过${maxPoint}`);
            }}
            placeholder='输入您期望兑换现金的积分数'
            type='number'
            className=' rounded-lg border-[2px] border-solid border-[rgba(70,109,180,0.2)]'
            renderButton={
              <>
                <View className=' border-l-gary4 border-l-solid border-l-[2px] leading-none pl-2'>
                  积分
                </View>
              </>
            }
          />

          {integral && (
            <View className=' text-center text-xs text-gary4 mt-2'>
              当前输入积分可兑换
              <Text className=' text-primary font-bold'>{calcMoney}</Text> 元
            </View>
          )}
        </View>

        <Button
          loading={loading}
          onClick={async () => {
            if (errorMessage) return;
            await runAsync({
              points: Number(integral || 0),
            });
            handleClose();
            props.onSuccess();
            Taro.showToast({ title: '提交成功' });
          }}
          type='primary'
          size='large'
          className='mt-2'
          disabled={
            txing || Boolean(!integral) || (errorMessage && true) || false
          }
        >
          {txing ? '您提交的申请正在审核中' : '提交申请'}
        </Button>
      </Popup>
    );
  }
  return {
    renderNode,
    open: () => setShow(true),
  };
}
